Page({
  data: {
    records: [],
    showToast: false,
    toastTitle: '',
    toastDuration: 2000,
    statusMap: {
      0: '待发货',
      1: '已发货',
      2: '已完成',
      3: '已取消'
    }
  },

  onLoad() {
    this.fetchExchangeRecords();
  },

  // 获取兑换记录
  fetchExchangeRecords() {
    const token = wx.getStorageSync('token');
    if (!token) {
      this.showCustomToast('请先登录');
      return;
    }

    wx.request({
      url: 'https://www.haoyuming.online/api/user/product/records',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 401) {
          // 清除登录信息
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          
          // 显示提示
          this.showCustomToast('登录已过期，请重新登录');
          
          // 跳转到登录页
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }, 1500);
          return;
        }
        
        if (res.data.code === 200) {
          // 格式化时间
          const records = res.data.data.map(item => ({
            ...item,
            exchangeTime: this.formatTime(item.exchangeTime)
          }));
          this.setData({ records });
        } else {
          this.showCustomToast(res.data.msg || '获取兑换记录失败');
        }
      },
      fail: () => {
        this.showCustomToast('网络错误，请稍后重试');
      }
    });
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return '';
    const date = new Date(timeStr);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack();
  },

  // 显示自定义提示
  showCustomToast(title, duration = 2000) {
    this.setData({
      showToast: true,
      toastTitle: title,
      toastDuration: duration
    });
  },

  // 提示隐藏回调
  onToastHide() {
    this.setData({
      showToast: false,
      toastTitle: ''
    });
  }
}); 